// static/js/script.js
// 公交智能调度系统 - 前端交互核心脚本

document.addEventListener('DOMContentLoaded', function() {
    // ================== 初始化功能 ==================
    console.log('公交调度系统脚本初始化');
    initDashboardClock();
    initSidebarNavigation();
    initFormValidation();
    initDataTables();
    initAutoRefresh();
    initModals();

    // ================== 侧边栏导航激活状态 ==================
    function initSidebarNavigation() {
        const currentPath = window.location.pathname;
        const navLinks = document.querySelectorAll('.nav-link');

        navLinks.forEach(link => {
            const href = link.getAttribute('href');
            // 匹配当前路径
            if (currentPath === href || currentPath.startsWith(href + '/')) {
                link.classList.add('active');
            } else {
                link.classList.remove('active');
            }
        });

        console.log('导航激活状态设置完成');
    }

    // ================== 表单验证增强 ==================
    function initFormValidation() {
        // 为所有表单添加提交事件
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', function(e) {
                let valid = true;

                // 检查必填字段
                const requiredFields = this.querySelectorAll('[required]');
                requiredFields.forEach(field => {
                    if (!field.value.trim()) {
                        valid = false;
                        field.classList.add('is-invalid');
                    }
                });

                // 特定表单的自定义验证
                if (this.id === 'add-schedule-form') {
                    const departureTime = this.querySelector('input[name="departure_time"]');
                    if (departureTime && new Date(departureTime.value) < new Date()) {
                        valid = false;
                        departureTime.classList.add('is-invalid');
                        const feedback = departureTime.nextElementSibling || document.createElement('div');
                        feedback.className = 'invalid-feedback';
                        feedback.textContent = '发车时间必须是将来的时间';
                        if (!departureTime.nextElementSibling) {
                            departureTime.parentNode.appendChild(feedback);
                        }
                    }
                }

                if (!valid) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                this.classList.add('was-validated');
            });
        });

        // 清除输入时移除错误样式
        document.querySelectorAll('.form-control').forEach(input => {
            input.addEventListener('input', function() {
                this.classList.remove('is-invalid');
                const feedback = this.nextElementSibling;
                if (feedback && feedback.classList.contains('invalid-feedback')) {
                    feedback.remove();
                }
            });
        });

        console.log('表单验证增强初始化完成');
    }

    // ================== 数据表格功能 ==================
    function initDataTables() {
        const tables = document.querySelectorAll('table');
        if (!tables.length) return;

        tables.forEach(table => {
            // 添加表头排序功能
            const headers = table.querySelectorAll('th[data-sortable="true"]');
            headers.forEach(header => {
                header.style.cursor = 'pointer';
                header.addEventListener('click', () => {
                    const index = Array.from(header.parentElement.children).indexOf(header);
                    sortTable(table, index);
                });
            });

            // 添加搜索框
            const searchDiv = document.createElement('div');
            searchDiv.className = 'mb-3 d-flex align-items-center';
            searchDiv.innerHTML = `
                <label for="searchTable" class="form-label me-2 mb-0">搜索:</label>
                <input type="text" id="searchTable" class="form-control form-control-sm" style="width: 200px;">
            `;
            table.parentNode.insertBefore(searchDiv, table);

            const searchInput = searchDiv.querySelector('input');
            searchInput.addEventListener('input', () => {
                filterTable(table, searchInput.value);
            });

            // 添加条目选择
            const perPageSelect = document.createElement('select');
            perPageSelect.className = 'form-select form-select-sm ms-2';
            perPageSelect.style.width = '80px';
            perPageSelect.innerHTML = `
                <option value="10">10</option>
                <option value="25">25</option>
                <option value="50">50</option>
                <option value="100">100</option>
            `;
            searchDiv.appendChild(perPageSelect);

            perPageSelect.addEventListener('change', () => {
                paginateTable(table, parseInt(perPageSelect.value));
            });

            // 初始化分页
            paginateTable(table, 10);
        });

        console.log('数据表格功能初始化完成');
    }

    function sortTable(table, columnIndex) {
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));
        const isAscending = !table.querySelector('th').classList.contains('sorted-asc');

        // 清除之前的排序状态
        table.querySelectorAll('th').forEach(th => {
            th.classList.remove('sorted-asc', 'sorted-desc');
            th.innerHTML = th.innerHTML.replace(' ↑', '').replace(' ↓', '');
        });

        // 设置新的排序状态
        const header = table.querySelectorAll('th')[columnIndex];
        header.classList.add(isAscending ? 'sorted-asc' : 'sorted-desc');
        header.innerHTML += isAscending ? ' ↑' : ' ↓';

        // 排序行
        rows.sort((a, b) => {
            const aValue = a.children[columnIndex].textContent.trim();
            const bValue = b.children[columnIndex].textContent.trim();

            // 尝试按数值排序
            if (!isNaN(aValue) && !isNaN(bValue)) {
                return isAscending ? aValue - bValue : bValue - aValue;
            }

            // 尝试按日期排序
            const dateA = new Date(aValue);
            const dateB = new Date(bValue);
            if (!isNaN(dateA) && !isNaN(dateB)) {
                return isAscending ? dateA - dateB : dateB - dateA;
            }

            // 默认按文本排序
            return isAscending
                ? aValue.localeCompare(bValue)
                : bValue.localeCompare(aValue);
        });

        // 重新添加行
        tbody.innerHTML = '';
        rows.forEach(row => tbody.appendChild(row));

        // 重新分页
        paginateTable(table, parseInt(document.querySelector('.form-select')?.value || 10));
    }

    function filterTable(table, searchTerm) {
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));
        const searchLower = searchTerm.toLowerCase();

        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(searchLower) ? '' : 'none';
        });
    }

    function paginateTable(table, perPage) {
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));
        const pageCount = Math.ceil(rows.length / perPage);
        let currentPage = 1;

        // 移除现有的分页控件
        const existingPagination = table.nextElementSibling;
        if (existingPagination && existingPagination.classList.contains('pagination-container')) {
            existingPagination.remove();
        }

        // 创建分页控件
        const paginationDiv = document.createElement('div');
        paginationDiv.className = 'pagination-container d-flex justify-content-end align-items-center mt-3';
        paginationDiv.innerHTML = `
            <div class="me-3">
                <span class="page-info">第<span id="current-page">1</span>页 / 共<span id="total-pages">${pageCount}</span>页</span>
            </div>
            <div class="btn-group">
                <button class="btn btn-sm btn-outline-secondary prev-btn" disabled>
                    <i class="fas fa-chevron-left"></i>
                </button>
                <button class="btn btn-sm btn-outline-secondary next-btn">
                    <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        `;

        table.parentNode.appendChild(paginationDiv);

        // 显示当前页
        function showPage(page) {
            rows.forEach((row, index) => {
                row.style.display = (index >= (page - 1) * perPage && index < page * perPage)
                    ? ''
                    : 'none';
            });

            document.getElementById('current-page').textContent = page;
            document.getElementById('total-pages').textContent = pageCount;

            // 更新按钮状态
            paginationDiv.querySelector('.prev-btn').disabled = page === 1;
            paginationDiv.querySelector('.next-btn').disabled = page === pageCount;
        }

        // 初始显示第一页
        showPage(1);

        // 事件监听
        paginationDiv.querySelector('.prev-btn').addEventListener('click', () => {
            if (currentPage > 1) {
                showPage(--currentPage);
            }
        });

        paginationDiv.querySelector('.next-btn').addEventListener('click', () => {
            if (currentPage < pageCount) {
                showPage(++currentPage);
            }
        });
    }

    // ================== 仪表盘功能 ==================
    function initDashboardClock() {
        const clockElement = document.getElementById('dashboard-clock');
        if (!clockElement) return;

        function updateClock() {
            const now = new Date();
            const dateStr = now.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                weekday: 'long'
            });

            const timeStr = now.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            });

            clockElement.innerHTML = `
                <div class="text-end text-muted">
                    ${dateStr} <span class="fw-bold">${timeStr}</span>
                </div>
            `;
        }

        updateClock();
        setInterval(updateClock, 1000);
        console.log('仪表盘时钟初始化完成');
    }

    function initAutoRefresh() {
        // 仅在仪表盘页面启用自动刷新
        if (!document.getElementById('dashboard-clock')) return;

        setInterval(() => {
            console.log('自动刷新仪表板数据...');
            // 在实际应用中，这里应该使用fetch获取最新数据
            // 然后更新仪表板中的卡片数据

            // 示例：更新卡片中的随机数据
            document.querySelectorAll('.card-body.text-center h1').forEach(card => {
                const value = parseInt(card.textContent);
                const change = Math.floor(Math.random() * 3) - 1; // -1, 0, 1
                card.textContent = value + change;
            });

            // 更新状态徽章
            const statusBadges = document.querySelectorAll('.badge');
            statusBadges.forEach(badge => {
                if (Math.random() > 0.8) { // 20% 概率改变状态
                    if (badge.classList.contains('bg-success')) {
                        badge.classList.replace('bg-success', 'bg-warning');
                        badge.textContent = '待发车';
                    } else if (badge.classList.contains('bg-warning')) {
                        badge.classList.replace('bg-warning', 'bg-success');
                        badge.textContent = '已完成';
                    }
                }
            });

        }, 15000); // 每15秒刷新一次

        console.log('仪表板自动刷新已启用 (15秒间隔)');
    }

    // ================== 模态框功能 ==================
    function initModals() {
        // 编辑/删除按钮点击事件
        document.querySelectorAll('.edit-btn, .delete-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const type = this.classList.contains('edit-btn') ? '编辑' : '删除';
                const target = this.dataset.target; // 如 bus, driver, schedule
                const id = this.dataset.id;

                showModal(type, target, id);
            });
        });
    }

    function showModal(action, entity, id) {
        // 创建模态框
        const modalId = `${action}-${entity}-modal`;
        let existingModal = document.getElementById(modalId);

        if (existingModal) {
            existingModal.remove();
        }

        const modal = document.createElement('div');
        modal.className = 'modal fade';
        modal.id = modalId;
        modal.tabIndex = -1;
        modal.innerHTML = `
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">${action} ${entity}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <p>确定要${action}ID为 <strong>${id}</strong> 的${entity}吗？</p>
                        ${action === '编辑' ? `
                            <div class="mb-3">
                                <label class="form-label">${entity}名称</label>
                                <input type="text" class="form-control" value="${entity} ${id}">
                            </div>
                        ` : ''}
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary confirm-btn">确认${action}</button>
                    </div>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        // 初始化Bootstrap模态框
        const modalInstance = new bootstrap.Modal(modal);
        modalInstance.show();

        // 确认按钮事件
        modal.querySelector('.confirm-btn').addEventListener('click', function() {
            console.log(`${action}操作已确认: ${entity} ${id}`);

            // 在实际应用中，这里应该调用API执行操作
            // 如: fetch(`/api/${entity}/${id}`, { method: action === '编辑' ? 'PUT' : 'DELETE' })

            // 显示操作成功消息
            showToast(`${action}操作成功`, `${entity} ${id} 已成功${action}`, 'success');

            // 关闭模态框
            modalInstance.hide();
        });

        // 模态框关闭后删除
        modal.addEventListener('hidden.bs.modal', function() {
            modal.remove();
        });
    }

    function showToast(title, message, type) {
        const toastContainer = document.getElementById('toast-container') || createToastContainer();
        const toastId = `toast-${Date.now()}`;

        const toast = document.createElement('div');
        toast.className = `toast align-items-center text-white bg-${type} border-0`;
        toast.id = toastId;
        toast.setAttribute('role', 'alert');
        toast.setAttribute('aria-live', 'assertive');
        toast.setAttribute('aria-atomic', 'true');
        toast.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">
                    <strong>${title}</strong><br>${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        `;

        toastContainer.appendChild(toast);

        // 初始化Bootstrap toast
        const toastInstance = new bootstrap.Toast(toast, {
            autohide: true,
            delay: 3000
        });

        toastInstance.show();
    }

    function createToastContainer() {
        const container = document.createElement('div');
        container.id = 'toast-container';
        container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        container.style.zIndex = '1060';
        document.body.appendChild(container);
        return container;
    }
});